var utils = require('../../utils/utils.js');
const app = getApp()
var timer;
var autoTimer;

Page({
  data: {
    client: null,
    deviceData: {},
    myintervalid:0,
    device:null,
    connected: false,
    readyRec:false,
    hexSend:false,
    hexRec:false,
    chs: [], 
    deviceadd:"  ",
    windowHeight: 0,// 页面总高度将会放在这里
    navbarHeight: 0,// navbar的高度
    headerHeight: 0,// header的高度
    scrollViewHeight: 300, // scroll-view的高度
    recdata:"",
    rxCount:0,
    txCount:0,
    rxRate:0,
    txRate:0,
    // connectState:"正在连接",
    connectState:"连接蓝牙",
    reconnect:"连接中...",
    timRX:0,
    timTX:0,
    sendText:"",
    autoSendInv:50,
    autosendEn:false,
    autosendText:"自动发送",
    showModal:false,
    showModalStatus:false,
    showTips:"",
  },  
  onLoad: function (options) {
    var that = this
    // this.queryDeviceData()
    // that.data.myintervalid = setInterval(function () {
    //   that.onShow()
    // }, 5000)
  },
  onShow: function (e) {
    var that = this
    app.readSetting()
    that.data.device = app.globalData.ble_device
    that.data.readyRec = false
    that.setData({
      autoSendInv : app.globalData.mautoSendInv,
      sendText : app.globalData.msendText,
    })
   // console.log("start ", this.data.autoSendInv, this.data.sendText)
   that.Countdown() 
    //this.showModalTips("开始连接设备....")
    if (that.data.device == null){
      return
    }
    const deviceId = that.data.device.deviceId
    that.setData({
      deviceadd: "MAC " + deviceId
    })
    const name = that.data.device.name
    console.log("device = ", that.data.device)
    that.serviceu = app.globalData.mserviceuuid.toUpperCase()
    that.txdu = app.globalData.mtxduuid.toUpperCase()
    that.rxdu = app.globalData.mrxduuid.toUpperCase()
    console.log("target uuids = ", that.serviceu, that.txdu, that.rxdu)
    // wx.setNavigationBarTitle({
    //   title: "正在连接 " + that.data.device.name
    // })
    that.setData({
      connectState: "正在连接"
    })
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          connected: true,
          name,
          deviceId,
          connectState: "读取服务",
          reconnect:"断开连接"
        })
        // wx.setNavigationBarTitle({
        //   title: "已连接 " + this.data.device.name
        // })
        //this.showModalTips("读取BLE所有服务")
        this.getBLEDeviceServices(deviceId)
      }
    })
  },
/**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () 
  {
    console.warn("onHide goto disconnect")
    if (this.data.connected) {
      wx.closeBLEConnection({
        deviceId: this.data.deviceId
      })
      this.setData({
        connected: false,
        reconnect: "重新连接",
        connectState: "已断开",
      })
      // wx.setNavigationBarTitle({
      //   title: "已断开 " + this.data.device.name
      // })
      console.warn("DisConnect ", this.data.deviceId)
    }
  },
    /**
   * 生命周期函数--监听页面卸载
   */
   onUnload: function () {
     app.saveSetting(this.data.autoSendInv, this.data.sendText)
     if (this.data.connected) {
       wx.closeBLEConnection({
         deviceId: this.data.deviceId
       })
       console.warn("DisConnect ", this.data.deviceId)
       this.data.connected=false
     }
  },
  //countdown
  Countdown() {
    var that = this;
    timer = setTimeout(function () {
      //console.log("----Countdown----");
      that.setData({
        rxRate: that.data.timRX*2,
        txRate: that.data.timTX*2,
      })
      that.setData({
        timRX: 0,
        timTX: 0,
      })
      that.Countdown();
    }, 500);
  }, 
  getBLEDeviceServices(deviceId) {
    var that = this
    this.data.readyRec = false
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        var isService = false
        console.log("service size = ", res.services.length)
        for (let i = 0; i < res.services.length; i++) {
         // if (res.services[i].isPrimary) {
          if (this.serviceu == res.services[i].uuid){
            //this.showModalTips(this.serviceu+"\r找到服务UUID，正在读取所有特征值")
            isService = true
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            this.setData({
              connectState: "获取特征值"
            })
            }
        }
        if (!isService){ //没有找到服务
          this.setData({
            connectState: "UUID错误"
          })
          this.showModalTips(this.serviceu +"\r找不到目标服务UUID  请确认UUID是否设置正确或重新连接")
        }
      }
    })
  },
  getBLEDeviceCharacteristics(deviceId, serviceId) {
   const that = this
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        var ismy_service = false
        console.log("compute ", serviceId, this.serviceu)
        if (serviceId == this.serviceu) {
          ismy_service = true
          console.warn("this is my service ")
        }
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (ismy_service){
            console.log("-----------------------")
          }
          console.log("this properties = ", item.properties)
          if (item.properties.read) {
            console.log("[Read]", item.uuid)
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            console.log("[Write]",item.uuid)
            this._deviceId = deviceId
            if (ismy_service && (this.txdu == item.uuid)){
              console.warn("find write uuid  ready to ", item.uuid)
              this._characteristicId = item.uuid
              this._serviceId = serviceId
             // this.showModalTips(this.txdu+ "\r找到发送特征值")
            }
            //this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            console.log("[Notify]", item.uuid)
            if (ismy_service && (this.rxdu == item.uuid)){
              console.warn("find notity uuid try enablec....", item.uuid)
             // this.showModalTips(this.rxdu + "\r正在开启通知...")
              wx.notifyBLECharacteristicValueChange({  //开启通知
                deviceId,
                serviceId,
                characteristicId: item.uuid,
                state: true, 
                success(res) {
                  console.warn('notifyBLECharacteristicValueChange success', res.errMsg)
                  that.setData({
                    connectState: "连接成功"
                  })
                 // that.showModalTips(that.rxdu + "\r开启通知成功")
                  that.data.readyRec=true
                }
              })
            }
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听，保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      var buf = new Uint8Array(characteristic.value)
      var nowrecHEX = utils.ab2hex(characteristic.value)
      console.warn("rec: ", nowrecHEX, characteristic.characteristicId)
      var recStr = utils.ab2Str(characteristic.value)
      console.warn("recstr: ", recStr, characteristic.characteristicId)
      if (this.rxdu != characteristic.characteristicId){
        console.error("no same : ", this.rxdu, characteristic.characteristicId)
        return
      }
      if (!this.data.readyRec)return
      var mrecstr
      if (this.data.hexRec){
        mrecstr = nowrecHEX
      }else{
        mrecstr = recStr
      }
      if (this.data.recdata.length>3000){
        this.data.recdata = this.data.recdata.substring(mrecstr.length, this.data.recdata.length)
      }
      console.warn("RXlen: ", buf.length)
      console.log("mrecstr is ", mrecstr)
      console.log("recdata is ", this.data.recdata)
      this.data.recdata = this.data.recdata + mrecstr
      // 将数据取出来，#25.1,,10,100,56#
      var arr = mrecstr.match(/\d+(.\d+)?/g); 
      console.log("recv data ", arr);
      // 组装json数据
      var jsonObj = {"temp":"-", "pulse":"-", "blood_oxygen":"-"};
      jsonObj.temp = arr[0]
      jsonObj.pulse = arr[1]
      jsonObj.blood_oxygen = arr[2]

      this.setData({
        // recdata: this.data.recdata,
        rxCount: this.data.rxCount + buf.length,
        timRX: this.data.timRX+buf.length,
        deviceData: jsonObj,
      })
      // 删除上面操作的json数据，保留后面数据
      arr=str.split('}');
      this.data.recdata = arr[1]

    })
  },
  writeBLECharacteristicValue() {
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, Math.random() * 255 | 0)
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._deviceId,
      characteristicId: this._characteristicId,
      value: buffer,
    })
  },
  gosend(sendText)
  {
    if (!this.data.connected){
      this.showModalTips("请先连接BLE设备...")
      return
    }
    var that = this;
    // var hex = this.data.sendText //要发送的数据
    var hex = sendText;
    var buffer1
    if (this.data.hexSend){ //十六进制发送
      var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
        return parseInt(h, 16)
      }))
      console.log("hextobyte ", typedArray)
      buffer1 = typedArray.buffer
    }else{ //string发送
      var strbuf = new Uint8Array(utils.stringToBytes(hex))
      console.log("strtobyte ", strbuf)
      buffer1 = strbuf.buffer
    }
    console.log("Txbuf = ",buffer1)
    if (buffer1==null)return
    const txlen = buffer1.byteLength
    wx.writeBLECharacteristicValue({
      deviceId: that._deviceId,
      serviceId: that._serviceId,
      characteristicId: that._characteristicId,
      value: buffer1,
      success: function (res) {
        // success
        that.setData({
          txCount: that.data.txCount + txlen,
          timTX:that.data.timTX+txlen
        })
        console.log("success  指令发送成功");
        console.log(res);
      },
      fail: function (res) {
        // fail
        console.log(res);
      },
      complete: function (res) {
        // complete
      }
    })
  }, 

  // {"temp":10, "pulse":20, "blood_oxygen":50}

  btn_connect_bluetooth: function (event) {
    console.log("btn bluetooth connect.....")
    wx.navigateTo({
      url: '/pages/find/find',
    })
  },
  btn_send : function (event)
  {
    var that = this
    console.log("ready to send data......")
    that.gosend("hello world...")
  }
})